/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.services;

import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.IBinder;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;

import com.phonebooksharing.android.R;
import com.phonebooksharing.android.activities.main.MainContainerActivity;
import com.phonebooksharing.android.activities.pref.PreferencesActivity;
import com.phonebooksharing.android.async.DashboardUpdaterTask;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.LocationUtil;
import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.dto.LocationItem;
import com.phonebooksharing.dto.ReturnItem;

public class LocationUpdaterService extends Service {
    
    public static void schedule(Context context) {
        final Intent intent = new Intent(context, LocationUpdaterService.class);
        final PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
        
        SharedPreferences pref = context.getSharedPreferences(PreferencesActivity.PREFERENCE_FILE_NAME, MODE_PRIVATE);
        
        //default is 30 min
        int UPDATES_CHECK_INTERVAL = pref.getInt(PreferencesActivity.PREF_NEARBY_FREQUENCY, 30) * 60 * 1000;

        Calendar c = new GregorianCalendar();
        c.add(Calendar.DAY_OF_YEAR, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(pending);
//        if (DEBUG) {
        
        long nextTrigger = SystemClock.elapsedRealtime() + (2 * 60 * 1000);//schedule to run 2 min after the app starts
        
            alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, nextTrigger,
                    UPDATES_CHECK_INTERVAL, pending);
//        } else {
//            alarm.setRepeating(AlarmManager.RTC, c.getTimeInMillis(),
//                    UPDATES_CHECK_INTERVAL, pending);
//        }
    }
    
    private LocationUpdaterTask task;
    
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        (task = new LocationUpdaterTask()).execute(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (task != null && task.getStatus() == NetworkHandlerTask.Status.RUNNING) {
            task.cancel(true);
        }
    }

    public IBinder onBind(Intent intent) {
        return null;
    }

    private class LocationUpdaterTask extends NetworkHandlerTask<Context, Object, Void> {
        private SharedPreferences mPreferences;
        
        @Override
        public void onPreExecute() {
            mPreferences = getSharedPreferences(PreferencesActivity.PREFERENCE_FILE_NAME, MODE_PRIVATE);
        }
        
        @Override
        public Void doInBackground(Context... params) {
            final Context cx = params[0];
            try {
                Global.loadConfig(cx);

                final LocationItem li;
                if (mPreferences.getBoolean(PreferencesActivity.PREF_USE_MANUAL_LOCATION, false)) {
                    li = LocationUtil.getManualLocationItem(cx, mPreferences.getString(PreferencesActivity.PREF_MANUAL_LOCATION, ""));
                } else {
                    li = LocationUtil.getCurrentLocationItem(cx);
                }
                
                li.accurancy = mPreferences.getInt(PreferencesActivity.PREF_NEARBY_ACCURANCY, 3);

                final String url = String.format(Global.LOCATION_SERVLET_URL, "u");
                final ReturnItem ri = (ReturnItem) doNetworkPost(url, li);
                if (!ri.isOK()) {
                    // TODO: do something
                }

                publishProgress(0);// if went well
            } catch (IOException e) {
                Log.e(Global.LOG_TAG, "are you connected to internet???", e);
                cancel(true);
            } catch (Exception e) {
                e.printStackTrace();
                cancel(true);
            }
            return null;
        }
        
        @Override
        public void onPostExecute(Void aVoid) {
            new DashboardTask().execute(getBaseContext());
        }
    }
    
    class DashboardTask extends DashboardUpdaterTask {
        private SharedPreferences mPreferences;
        private NotificationManager mManager;
        
        @Override
        public void onPreExecute() {
            mPreferences = getSharedPreferences(PreferencesActivity.PREFERENCE_FILE_NAME, MODE_PRIVATE);
            mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }
        
        @Override
        protected void onProgressUpdate(Object... values) {
            super.onProgressUpdate(values);
            
            if (mPreferences.getBoolean(PreferencesActivity.PREF_NEARBY_NOTIFY_ENABLE, true)) {
                final Intent intent = new Intent(LocationUpdaterService.this, MainContainerActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

                Notification notification = new Notification(R.drawable.notify,
                        "Phonebook Sharing Dashboard",
                        System.currentTimeMillis());
                
                notification.setLatestEventInfo(LocationUpdaterService.this,
                        "Dashboard Updated",
                        "Your dashboard has been updated",
                        PendingIntent.getActivity(LocationUpdaterService.this, 0, intent,
                                PendingIntent.FLAG_CANCEL_CURRENT));

                if (mPreferences.getBoolean(PreferencesActivity.PREF_NEARBY_NOTIFY_VIBRATE, false)) {
                    notification.defaults |= Notification.DEFAULT_VIBRATE;
                }

                String ringtoneUri = mPreferences.getString(PreferencesActivity.PREF_NEARBY_NOTIFY_RINGTONE, null);
                notification.sound = TextUtils.isEmpty(ringtoneUri) ? null : Uri.parse(ringtoneUri);

                mManager.notify(Global.NOTIFICATION_GUID, notification);
            }
        }
        
        @Override
        public void onPostExecute(Void aVoid) {
            // pref = null;
            stopSelf();
        }
    }
}